package com.ruoyi.project.system.controller;

import com.alipay.api.response.AlipayFundTransCommonQueryResponse;
import com.alipay.api.response.AlipayFundTransToaccountTransferResponse;
import com.ruoyi.common.utils.AlibabaApi;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.TencentApi;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.interceptor.annotation.RepeatSubmit;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.system.domain.SysExtract;
import com.ruoyi.project.system.domain.SysUser;
import com.ruoyi.project.system.domain.vo.TiXianVo;
import com.ruoyi.project.system.service.ISysExtractService;
import com.ruoyi.project.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 提现Controller
 *
 */
@RestController
@RequestMapping("/extract")
public class SysExtractController extends BaseController {

    @Autowired
    private ISysExtractService sysExtractService;

    @Autowired
    private ISysUserService iSysUserService;

    @GetMapping("/tiXianList")
    public AjaxResult queryTiXianList() {
        return success(sysExtractService.queryTiXianList());
    }

    /**
     * 用户发起提现
     */
    @RepeatSubmit
    @GetMapping("/userTx")
    public AjaxResult userTx() {
        TiXianVo tiXianVo = sysExtractService.queryTiXianList();
        if (tiXianVo.getCode() == 400) {
            return AjaxResult.error("提现列表为空！");
        }
        return success(sysExtractService.addTXLIst(tiXianVo ));
    }

    /**
     * 管理系统发起转账
     */
    @GetMapping("/admTxzz/{extractId}")
    public AjaxResult admTxzz(@PathVariable("extractId") String extractId) {
        SysExtract sysExtract = sysExtractService.selectSysExtractByExtractId(extractId);
        if ("已转账".equals(sysExtract.getStatus()) || "转账中".equals(sysExtract.getStatus())) {
            return error(sysExtract.getStatus());
        } else {
            try {
                AlipayFundTransToaccountTransferResponse transfer = AlibabaApi.transfer(sysExtract);
                SysExtract extract;
                if ("10000".equals(transfer.getCode())) {
                    extract = new SysExtract(transfer.getOutBizNo(), transfer.getOrderId(), transfer.getPayDate(), "已转账");
                    sysExtractService.updateSysExtract(extract);
                    // 公众号通知
                    SysUser sysUser = iSysUserService.selectUserById(sysExtract.getUserId());
                    if (StringUtils.isNotEmpty(sysUser.getOpenId())) {
                        sysExtract.setTransDate(transfer.getPayDate());
                        TencentApi.pushMessage(sysUser.getOpenId(), sysExtract);
                    }
                    return success(transfer.getMsg());
                } else {
                    extract = new SysExtract(transfer.getOutBizNo(), "失败");
                    extract.setRemark(transfer.getSubMsg());
                    sysExtractService.updateSysExtract(extract);
                    return error(transfer.getSubMsg());
                }
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
    }

    /**
     * 管理系统发起查账
     */
    @PostMapping("/query")
    public AjaxResult query(SysExtract sysExtract) {
        try {
            AlipayFundTransCommonQueryResponse transfer = AlibabaApi.query(sysExtract);
            SysExtract extract;
            if ("10000".equals(transfer.getCode()) && "SUCCESS".equals(transfer.getStatus())) {
                extract = new SysExtract(transfer.getOutBizNo(), transfer.getOrderId(), transfer.getPayDate(), "已转账");
                sysExtractService.updateSysExtract(extract);
                return success(transfer.getMsg());
            } else {
                extract = new SysExtract(transfer.getOutBizNo(), "失败");
                extract.setRemark(transfer.getSubMsg());
                sysExtractService.updateSysExtract(extract);
                return success(transfer.getSubMsg());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 查询某用户提现记录
     */
    @GetMapping("/userExtractList")
    public AjaxResult userExtractList(SysExtract sysExtract) {
        sysExtract.setUserId(SecurityUtils.getUserId());
        return success(sysExtractService.selectSysExtractList(sysExtract));
    }

    /**
     * 查询提现列表
     */
    @PreAuthorize("@ss.hasPermi('system:extract:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysExtract sysExtract) {
        startPage();
        List<SysExtract> list = sysExtractService.selectSysExtractList(sysExtract);
        return getDataTable(list);
    }

    /**
     * 导出提现列表
     */
    @PreAuthorize("@ss.hasPermi('system:extract:export')")
    @Log(title = "提现", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysExtract sysExtract) {
        List<SysExtract> list = sysExtractService.selectSysExtractList(sysExtract);
        ExcelUtil<SysExtract> util = new ExcelUtil<SysExtract>(SysExtract.class);
        util.exportExcel(response, list, "提现数据");
    }

    /**
     * 获取提现详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:extract:query')")
    @GetMapping(value = "/{extractId}")
    public AjaxResult getInfo(@PathVariable("extractId") String extractId) {
        return success(sysExtractService.selectSysExtractByExtractId(extractId));
    }

    /**
     * 新增提现
     */
    @PreAuthorize("@ss.hasPermi('system:extract:add')")
    @Log(title = "提现", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysExtract sysExtract) {
        return toAjax(sysExtractService.insertSysExtract(sysExtract));
    }

    /**
     * 修改提现
     */
    @PreAuthorize("@ss.hasPermi('system:extract:edit')")
    @Log(title = "提现", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysExtract sysExtract) {
        return toAjax(sysExtractService.updateSysExtract(sysExtract));
    }

}
